package com.tsfyun.scm.service.impl.user;

import cn.hutool.core.collection.CollUtil;
import com.tsfyun.common.base.config.OrikaBeanMapper;
import com.tsfyun.common.base.extension.ServiceImpl;
import com.tsfyun.common.base.util.RequestUtils;
import com.tsfyun.scm.dto.user.LogLoginDTO;
import com.tsfyun.scm.entity.user.LogLogin;
import com.tsfyun.scm.entity.user.Person;
import com.tsfyun.scm.mapper.user.LogLoginMapper;
import com.tsfyun.scm.service.user.ILogLoginService;
import com.tsfyun.scm.util.TsfWeekendSqls;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class LogLoginServiceImpl extends ServiceImpl<LogLogin> implements ILogLoginService {

    @Autowired
    private OrikaBeanMapper beanMapper;

    @Autowired
    private LogLoginMapper logLoginMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(LogLoginDTO dto) {
        LogLogin logLogin = beanMapper.map(dto,LogLogin.class);
        super.saveNonNull(logLogin);
    }

    @Override
    public LogLogin personLastLogin(Long personId,String device) {
        Example example = Example.builder(LogLogin.class).where(TsfWeekendSqls.<LogLogin>custom()
                .andEqualTo(false,LogLogin::getPersonId,personId)
                .andEqualTo(true,LogLogin::getDevice,device)).build();
        example.setOrderByClause("date_created desc");
        List<LogLogin> logLogins = logLoginMapper.selectByExampleAndRowBounds(example,new RowBounds(0,2));
        if(CollUtil.isNotEmpty(logLogins)){
            if(logLogins.size()>1){
                return logLogins.get(1);
            }else{
                return logLogins.get(0);
            }
        }
        LogLogin logLogin = new LogLogin();
        logLogin.setDateCreated(LocalDateTime.now());
        return logLogin;
    }
}
